/*
by txdnet.cn tonydon
 */

package txdnet.util.uploader.apache.fileupload;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import txdnet.util.FileUtil;
import txdnet.util.Logger;
/**
 *
 * @author txdnet
 */
public class MutiFileUpload extends FileUploadBase{


    private Map<String, FileItem> files;// 保存上传的文件
    private int filesSize = 0; // 所有文件的总大小
    private ArrayList<String> saveFileList = null;


    public void parseRequest(HttpServletRequest request){

        files = new TreeMap<String, FileItem>(); // 顺序保存文件

        // Create a factory for disk-based file items

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(sizeThreshold);

        if (repository != null) factory.setRepository(repository);

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setHeaderEncoding(encoding);

        try{
            List<FileItem> items =  upload.parseRequest(request);

            for (FileItem item : items){
                if (item.isFormField()){
                   parameters.put(item.getFieldName(), item.getString(encoding));
                } else{
                    if (super.isValidFile(item)){
                    files.put(item.getFieldName(), item);
                    filesSize += item.getSize();
                    }
                }
            }

        } catch (Exception ex){
            Logger.error(MutiFileUpload.class, ex.toString());
        }
    }

    /** *//** *//** *//**
     * 上传文件, 调用该方法之前必须先调用 parseRequest(HttpServletRequest request)
     * @param parent 文件存储的目录
     * @throws Exception
     * 用filenameStr充当新文件前缀
     */
    public void upload(String parent, String filenameStr) throws Exception{
        if (files.isEmpty())return;
        if (sizeMax > -1 && filesSize > super.sizeMax){
            String message = String.format("the request was rejected because its size (%1$s) exceeds the configured maximum (%2$s)", filesSize, super.sizeMax);
          throw new SizeLimitExceededException(message, filesSize, super.sizeMax);
        }
        FileItem item ;
        File file ;
        int cnt = 0;
        saveFileList = new ArrayList<String>();
        String tmpRndFile ;
        for (String key : files.keySet()){
            item = files.get(key);
            // 以下为自动生成随机文件名
            tmpRndFile=(new StringBuilder()).append(filenameStr).append(".").append(cnt).append(".").append(FileUtil.getFileExt(item.getName())).toString();
            file = new File(parent, tmpRndFile);
            item.write(file);
            saveFileList.add(cnt,tmpRndFile);
            cnt++;
            if(!item.isInMemory()){ item.delete(); }
        }
    }

      public void upload(String parent) throws Exception{
        if (files.isEmpty())return;
        if (sizeMax > -1 && filesSize > super.sizeMax){
            String message = String.format("the request was rejected because its size (%1$s) exceeds the configured maximum (%2$s)", filesSize, super.sizeMax);
          throw new SizeLimitExceededException(message, filesSize, super.sizeMax);
        }
        FileItem item ;
        File file ;
        int cnt = 0;
        saveFileList = new ArrayList<String>();
        String tmpRndFile ;
        for (String key : files.keySet()){
            item = files.get(key);
            tmpRndFile=FileUtil.getFileName(item.getName());
            file = new File(parent, tmpRndFile);
            item.write(file);
            saveFileList.add(cnt,tmpRndFile);
            cnt++;
            if(!item.isInMemory()){ item.delete(); }
        }
    }

    public Map<String, FileItem> getFiles(){
        return files;
    }

    public ArrayList getSaveFileList(){
        return saveFileList;
    }

    public int getFilesSize(){
        return filesSize;
    }

}